import numpy as np
import matplotlib.pyplot as plt
import matplotlib

X = [1.0, 2.0, 3.0]
Y = [2.0, 4.0, 6.0]


def forward(x, w):
    return x * w

def loss(y_pred, y):
    return (y_pred - y) ** 2

w_list = [] # 手动设置多个 w 取值
mes_list = [] # 平均损失

for w in np.arange(0.0, 4.1, 0.1): # w 的取值从 0.0， 0.1， 0.2，。。。4.0
    print("w= ", w)
    loss_sum = 0
    for x, y in zip(X, Y):
        y_pred = forward(x, w)
        loss_val = loss(y_pred, y)
        loss_sum += loss_val
        print('\t', x, y, y_pred, loss_val)
    print("MSE= ", loss_sum / 3)
    w_list.append(w)
    mes_list.append(loss_sum / 3)

# 绘图
matplotlib.use('TkAgg')
plt.plot(w_list, mes_list)
plt.ylabel("MES_Loss")
plt.xlabel("w")
plt.show()

